package com.hxb.ruifeng.controller;


import com.hxb.ruifeng.entity.enums.RedisKeyEnum;
import com.hxb.ruifeng.entity.vo.UserVo;
import com.hxb.ruifeng.util.JsonUtil;
import com.hxb.ruifeng.util.JwtTokenUtil;
import com.hxb.ruifeng.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@RestController
public class BaseController{

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 由网关 传入最新的user信息
     * @return
     */
    public UserVo loginUser() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String authToken = request.getHeader(RedisKeyEnum.REDIS_KEY_HEADER_INFO.getKey());
        authToken = (String) redisUtil.get(RedisKeyEnum.REDIS_KEY_USER_INFO.getKey()+authToken);
        //解析token
        if (!StringUtils.isEmpty(authToken)) {
            //解析token
            String userInfo = jwtTokenUtil.getUsernameFromToken(authToken);
            return JsonUtil.jsonToBean(userInfo, UserVo.class);
        }
        return null;
    }

}
